package com.abbas.abchat.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.abbas.abchat.AbChatApplication;
import com.abbas.abchat.R;
import com.abbas.abchat.adapter.UserListAdapter;
import com.abbas.abchat.dao.AccountDao;
import com.abbas.abchat.dao.impl.AccountDaoImpl;
import com.abbas.abchat.entity.Account;
import com.abbas.abchat.entity.Item;
import com.abbas.abchat.utils.SpUtils;
import com.abbas.abchat.utils.TextLengthUtils;

import java.util.ArrayList;
import java.util.List;

public class UserInfoActivity extends BaseActivity {

    private ImageButton ibBack;
    private TextView title;
    private ListView lv;

    private UserListAdapter adapter;

    private final int REQUEST_CODE = 0x021;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_user_info;
    }

    @Override
    protected void init() {
        ibBack = (ImageButton) findViewById(R.id.ib_back);
        title = (TextView) findViewById(R.id.title);
        lv = (ListView) findViewById(R.id.lv);

        initData();
    }

    private void initData(){
        List<Item> items = new ArrayList<>();
        items.add(new Item("头像",AbChatApplication.getAccount().getImgPath()));
        items.add(new Item("昵称", AbChatApplication.getAccount().getName()));

        if (adapter == null){
            adapter = new UserListAdapter(this,items);
            lv.setAdapter(adapter);
        }else {
            adapter.setItems(items);
        }
    }

    @Override
    protected void initEvent() {

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0:
                        Intent intent = new Intent(Intent.ACTION_PICK,
                                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent,REQUEST_CODE);
                        break;
                    case 1:
                        View et = LayoutInflater.from(UserInfoActivity.this).inflate(R.layout.et,null,false);
                        EditText mEt = (EditText) et;
                        AlertDialog alertDialog = new AlertDialog.Builder(UserInfoActivity.this)
                                .setTitle("取一个你喜欢的名字吧~")
                                .setView(et)
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        final String name = mEt.getText().toString().trim();
                                        if (!TextLengthUtils.isOverTo(name,20)){
                                            AccountDao accountDao = new AccountDaoImpl(UserInfoActivity.this);
                                            Account account = AbChatApplication.getAccount();
                                            account.setName(name);
                                            try {
                                                final int result = accountDao.updateById(account);
                                                if (result <= 0){
                                                    showMessage("更改失败");
                                                }else {
                                                    showMessage("修改成功");
                                                    AbChatApplication.setAccount(account);
                                                    SpUtils.config(UserInfoActivity.this,SpUtils.LOGIN_ACCOUNT)
                                                            .putString(Account.NAME,name);
                                                    initData();
                                                }
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }else {
                                            showMessage("名字太太太长！");
                                        }
                                    }
                                })
                                .create();
                        alertDialog.show();
                        break;
                }
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE){
            if (data != null){
                final Uri uri = data.getData();
                final String path = getPath(uri);
                Log.i("path:",path);

                Account account = AbChatApplication.getAccount();
                AccountDao accountDao = new AccountDaoImpl(this);
                account.setImgPath(path);
                try {
                    final int result = accountDao.updateById(account);
                    if (result <= 0){
                        showMessage("修改失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                AbChatApplication.setAccount(account);
                SpUtils.config(this,SpUtils.LOGIN_ACCOUNT)
                        .putString(Account.IMAGE_PATH,path);
                showMessage("修改成功");
                initData();
            }

        }
    }

    // 根据系统相册选择的文件获取路径
    @SuppressLint("NewApi")
    private String getPath(Uri uri) {
//        int sdkVersion = Build.VERSION.SDK_INT;
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        // 高于4.4.2的版本
//        if (sdkVersion >= 19) {
        if (isKitKat && DocumentsContract.isDocumentUri(UserInfoActivity.this, uri)) {
            Log.e("TAG", "uri auth: " + uri.getAuthority());
            if (isExternalStorageDocument(uri)) {
                String docId = DocumentsContract.getDocumentId(uri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(id));
                return getDataColumn(this, contentUri, null, null);
            } else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(this, contentUri, selection, selectionArgs);
            } else if (isMedia(uri)) {
                String[] proj = {MediaStore.Images.Media.DATA};
                Cursor actualimagecursor = this.managedQuery(uri, proj, null, null, null);
                int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                actualimagecursor.moveToFirst();
                return actualimagecursor.getString(actual_image_column_index);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();
            return getDataColumn(this, uri, null, null);

        } else if ("file".equalsIgnoreCase(uri.getScheme())) { // File
            return uri.getPath();
        }
        return null;
    }

    private String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    private boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static boolean isMedia(Uri uri) {
        return "media".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}